import React, { Component } from 'react';
import {
  View,Text,StyleSheet,ScrollView,Image,TextInput,Modal
} from 'react-native';
import pxToDp from '../common/comm';
import * as DATA from '../data/data';
import {NavigationActions} from 'react-navigation';

export default class ResetPassword extends Component {

  constructor(props) {
    super(props);
    this.state = {
      phone:'',
      code: '',
      pwd_1: '',
      pwd_2: '',
      isModal: false,
      alertTxt: '',
      isCode: false,
      codeSecond:60
    }
  }

  static navigationOptions={
    headerTintColor:'#fff',
    headerTitle: '修改密码',
    headerStyle: {
      backgroundColor: DATA.BASE_COLOR,
      height: pxToDp(110)
    },
    headerTitleStyle: {
      color: '#fff',
      fontSize: pxToDp(34)
    },
    gesturesEnabled :true
  }

  //提示框3秒后消失
  _show(txt) {
    this.setState({
      isModal: true,
      alertTxt: txt
    });
    this.timer = setTimeout(() => {this._hide()},3000);
  }

  _hide() {
    this.setState({
      isModal:false
    })
  }

  componentWillUnMount() {
    this.timer && clearTimeout(this.timer);
    this.timer1 && clearInterval(this.timer1);
  }

  checkPhone() {
    var phone = this.state.phone; //手机号
    var pwd_1 = this.state.pwd_1;
    var pwd_2 = this.state.pwd_2;
    var pattern = /^1(3|4|5|7|8)\d{9}$/; //手机号格式
    var code = this.state.code; //验证码
    var patrn = /^(\w){6,20}$/; //密码格式
    isPhone = 1;
    if (phone == '') {
      isPhone = 0;
      this._show('请输入手机号码');
        return false;
    }
    if (!pattern.test(phone)) {
      this._show('请输入正确的手机号码');
        isPhone = 0;
        return false;
    }
    if (code == '') {
      this._show('请输入有效验证码！');
        return false;
    }
    if (pwd_1 == '') {
      this._show('密码不能为空');
        return false;
    }
    if (!patrn.test(pwd_1)) {
      this._show('请确认，密码为6-20位数字或者字母！');
        isPhone = 0;
        return false;
    }
    if (pwd_2 != pwd_1) {
      this._show('请确认，密码是否输入一致');
        return false;
    }
    return true;
  }

  _onPress() {
    let isCheck = this.checkPhone();
    let _that = this;
    //let md = forge.md.md5.create();
    //md.update(this.state.phone + this.state.pwd + DATA.mimi);
    //let valid = md.digest().toHex();
    if(isCheck) {
      let data2 = 'phone=' + this.state.phone + '&code=' + this.state.code + '&pwd=' + this.state.pwd_1;
      fetch(DATA.FORGET_URL, {
        method: "POST",
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: data2
      })
          .then((response) => {       // 数据解析方式
            if (response.ok) {
              return response.json();
            }
          })
          .then((responseData) => {       // 获取到的数据处理
            _that._show(responseData.msg);
            if (responseData.status == 1) {
              setTimeout(() => {
                //返回登录页面
                const resetActions = NavigationActions.reset({
                  index: 0,
                  actions: [NavigationActions.navigate({routeName: 'Login'})]
                });
                this.props.navigation.dispatch(resetActions);
              }, 3000);
            }
          })
          .catch((error) => { // 错误处理
            _that._show(error);
          })
          .done();
    }
  }

  getCodeTxt() {
    if (this.state.isCode) {
      return (
        <View style={styles.codeBox}>
          <Text style={styles.codeSecond}>{this.state.codeSecond}</Text>
          <Text style={styles.codeTxt}>秒后重发</Text>
        </View>
      );
    } else {
      return (<Text style={styles.code} onPress={()=>{this.getCode()}}>获取验证码</Text>);
    }
  }

  getCode() {
    let _that = this;
    let data2 = 'phone='+this.state.phone+'&code='+this.state.code+'&pwd='+this.state.pwd_1+'&type=forget';
    let timer1 = null;

    fetch(DATA.SENDCODE_URL, {
      method: "POST",
      headers:{'Content-Type': 'application/x-www-form-urlencoded' },
      body: data2
    })
        .then((response) => {       // 数据解析方式
          if (response.ok) {
            return response.json();
          }
        })
        .then((responseData) => {       // 获取到的数据处理
          _that._show(responseData.msg);
          if(responseData.status == 1){
            timer1 = setInterval(() => {
              _that.increaseSecond()
            },1000);
          }
        })
        .catch((error) => { // 错误处理
          _that._show('获取数据失败，请重试！');
        })
        .done();
  }

  increaseSecond() {
    if (this.state.codeSecond == 0){
      this.setState({
        isCode:false
      });
      this.timer1 && clearInterval(this.timer1);
      return;
    }
    this.setState({
      codeSecond: this.state.codeSecond - 1
    })
  }

  render() {
    return (
      <ScrollView
        contentContainerStyle={styles.contentContainer}
      > 
        <Modal
            animationType='fade'            // 淡入淡出
            transparent={true}              // 透明
            visible={this.state.isModal}    // 根据isModal决定是否显示
            onRequestClose={() => {this.onRequestClose()}}  // android必须实现
        >
            <View style={modalStyle.modalViewStyle}> 
                <View style={modalStyle.hudViewStyle}> 
                    <Text style={modalStyle.hudTextStyle}>{this.state.alertTxt}</Text>
                </View> 
            </View> 
        </Modal>  
        <Image source={{uri:DATA.ICON_IMG}} style={styles.img}></Image>
        <TextInput
          placeholder='手机号'
          style={[styles.input,{marginTop:pxToDp(30)}]}
          placeholderTextColor='#ccc'
          keyboardType='numeric'
          underlineColorAndroid='#aaa'
          onChangeText={(text) => {
            this.setState({
              phone:text
            })
          }}
        />
        <TextInput
          placeholder='验证码'
          style={styles.input}
          placeholderTextColor='#ccc'
          keyboardType='numeric'
          underlineColorAndroid='#aaa'
          onChangeText={(text) => {
            this.setState({
              code:text
            })
          }}
        />
        <TextInput
          placeholder='新密码(6-20位字符均可)'
          style={styles.input}
          placeholderTextColor='#ccc'
          underlineColorAndroid='#aaa'
          onChangeText={(text) => {
            this.setState({
              pwd_1:text
            })
          }}
        />
        <TextInput
          placeholder='确认密码(6-20位字符均可)'
          style={styles.input}
          placeholderTextColor='#ccc'
          underlineColorAndroid='#aaa'
          onChangeText={(text) => {
            this.setState({
              pwd_2:text
            })
          }}
        />
        <Text
          style={styles.login}
          onPress={() => {
            this._onPress();
          }}>重置密码</Text>
        {this.getCodeTxt()}
      </ScrollView>
    );
  }
  }

var styles = StyleSheet.create({
    contentContainer: {
      backgroundColor:'#fff',
      paddingTop:pxToDp(100),
      alignItems: 'center',
      height: pxToDp(970),
  },
    img:{
      width: pxToDp(132),
      height:pxToDp(193)  
  },
    input: {
      width: pxToDp(500),
      height:pxToDp(100)
    },
    login: {
      width: pxToDp(500),
      height: pxToDp(70),
      fontSize: pxToDp(36),
      backgroundColor: DATA.BASE_COLOR,
      color: "#fff",
      marginTop: pxToDp(30),
      textAlign: 'center',
      textAlignVertical: 'center',
      borderRadius: pxToDp(15),
    },
    code: {
      position:'absolute',
      right: pxToDp(80),
      top: pxToDp(450),
      color: '#fff',
      backgroundColor: DATA.BASE_COLOR,
      width: pxToDp(150),
      height: pxToDp(40),
      textAlignVertical:'center',
      textAlign: 'center',
      borderRadius:pxToDp(30)
  }  ,
    codeBox: {
      position:'absolute',
      right: pxToDp(80),
      top: pxToDp(450),
      backgroundColor: DATA.BASE_COLOR,
      width: pxToDp(150),
      height: pxToDp(40),
      borderRadius: pxToDp(30),
      flexDirection: 'row',
      paddingLeft:pxToDp(15),
      paddingTop:pxToDp(4),
    },
    codeSecond: {
      color:'#fff'
    },
    codeTxt: {
      color:'#fff'
    }
});
  
const modalStyle = StyleSheet.create({
  modalViewStyle: {
    position: 'absolute',
    top:pxToDp(900),
    alignSelf:'center'
  },
  hudViewStyle: {
    backgroundColor: 'rgba(0,0,0,0.5)',
    paddingLeft:pxToDp(15),
    paddingRight:pxToDp(15),
    paddingTop:pxToDp(10),
    paddingBottom: pxToDp(10),
    borderRadius:pxToDp(10)
  },
  hudTextStyle: {
    color:'#fff'
  }
})
